# -*- coding: utf-8 -*-
'''
@author: olivia.dou
Created on: 2022/10/16 16:06
desc:
'''
import time
from appium.options.ios import XCUITestOptions
from appium.webdriver.webdriver import WebDriver
from base.get_config import get_capabilities, get_cmd_executor
import base.globalvars as glo
import logging, os
from appium.options.android import UiAutomator2Options
from selenium.webdriver.support.wait import WebDriverWait
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support import expected_conditions as EC

from proj_spec.CLUE.mobile_po.clue_app_base_page import CLUEAppBasePage
from proj_spec.CLUE.mobile_po.main_page import MainPage
#from proj_spec.CLUE.mobile_po.wework_login_page import WeworkLoginPage


class App(CLUEAppBasePage):

    driver: WebDriver = None
    main_page: MainPage = None
    username = ""


    @classmethod
    def _launch_app(cls):
        caps = get_capabilities()
        if 'browserstack' in glo.get_value("config_name"):
            build_name = os.getenv("BROWSERSTACK_BUILD_NAME")
            print("****************************BROWSERSTACK_BUILD_NAME:%s" % os.getenv("BROWSERSTACK_BUILD_NAME"))
            if build_name !='' and build_name is not None:
                caps['bstack:options']['buildName'] = build_name
            print("****************************BROWSERSTACK_APP_ID: %s" % os.getenv("BROWSERSTACK_APP_ID"))
            app_id = os.getenv("BROWSERSTACK_APP_ID")
            if app_id !='' and app_id is not None:
                caps['app'] = app_id
            # 如果命令行有赋值则使用命令行赋的值，否则使用配置文件中的默认值/jenkins node环境变量
            caps['appium:deviceName'] = glo.get_value("device_name") if glo.get_value("device_name") is not None else caps['appium:deviceName']
            caps['platformName'] = glo.get_value("platform_name") if glo.get_value("platform_name") is not None else caps['platformName']
            caps['appium:platformVersion'] = glo.get_value("platform_version") if glo.get_value("platform_version") is not None else caps['appium:platformVersion']
            caps['app'] = glo.get_value("app_url") if glo.get_value("app_url") is not None else caps['app']
        elif 'lambdatest' in glo.get_value('config_name'):
            build_name = os.getenv('LT_BUILD_NAME')
            print("******************************build name is: %s************************************************" % build_name)
            if build_name !='' and build_name is not None:
                caps['lt:options']['build'] = build_name
            # 如果命令行有赋值则使用命令行赋的值，否则使用配置文件中的默认值/jenkins node环境变量
            caps['lt:options']['deviceName'] = glo.get_value("device_name") if glo.get_value(
                "device_name") is not None else caps['lt:options']['deviceName']
            caps['lt:options']['platformName'] = glo.get_value("platform_name") if glo.get_value("platform_name") is not None else caps['lt:options']['platformName']
            caps['lt:options']['platformVersion'] = glo.get_value("platform_version") if glo.get_value(
                "platform_version") is not None else caps['lt:options']['platformVersion']
            caps['lt:options']['app'] = glo.get_value("app_url") if glo.get_value("app_url") is not None else caps['lt:options']['app']
        if 'platformName' in caps and caps['platformName'].lower()=='android':
            options = UiAutomator2Options().load_capabilities(caps)
        else:
            options = XCUITestOptions().load_capabilities(caps)

        if 'lambdatest' in glo.get_value("config_name") or 'saucelab' in glo.get_value("config_name") or 'testingbot' in glo.get_value("config_name"):
            cls.driver = webdriver.Remote(get_cmd_executor(),caps)
        else:
            cls.driver = webdriver.Remote(get_cmd_executor(), options=options)

        cls.driver.implicitly_wait(glo.get_value("implicit_wait", 10))

        if 'wework' in glo.get_value("config_name"):
            # # 企业微信运行方式，登录需要微信认证，
            # cls.driver.start_activity(get_value("WebDriver","appPackage"),get_value("WebDriver","appActivity"))
            # try:
            #     wework_login_page = WeworkLoginPage(cls.driver)
            #     assert wework_login_page.login_by_wechat() is True, "登录失败" #尝试登录
            # except Exception as e:
            #     if glo.get_value("skip_login")=='True': #跳过登录，继续下面流程
            #         pass
            #     else:
            #         logging.error("登录失败：%s"%e)
            #         raise e

            #workstation = cls.driver.find_elements("id", "com.tencent.wework:id/e14")[-2]
            workstation = cls.driver.find_element(AppiumBy.XPATH,
                                              "//*[contains(@resource-id, 'com.tencent.wework') and contains(@text,'工作台')]")
            workstation.click()
            try:
                # print("scroll...")
                cls.find_element_and_click(cls,(AppiumBy.ANDROID_UIAUTOMATOR,
                                        'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().text("银行数字化营销"));'))
                # cls.driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
                #                                  'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().text("银行数字化营销").instance(0));')
                # bad practice to call instance method with classmethod when treating it like instance method and add class as instance
                # how to resolve?
            except Exception as e:
                cls.swipe_up(cls, (AppiumBy.ID, "com.tencent.wework:id/e6p"))
                cls.driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("银行数字化营销")').click()
        else:
            if "用户协议和隐私政策" in cls.driver.page_source:
                try:
                    privacy_element = WebDriverWait(cls.driver, 1).until(
                        EC.element_to_be_clickable(
                            (AppiumBy.ID, f"{cls.driver.capabilities['appPackage']}:id/btn_custom_privacy_sure"))
                    )
                    privacy_element.click()
                except Exception as e:
                    logging.warning("no privacy element found:")

            if not ('autoGrantPermissions' in cls.driver.capabilities and cls.driver.capabilities['autoGrantPermissions'] is True): #默认为False
                try:
                    access_element = WebDriverWait(cls.driver, ).until(
                        EC.element_to_be_clickable((AppiumBy.ID, "com.android.packageinstaller:id/permission_allow_button"))
                    )
                    access_element.click()
                except Exception as e:
                    logging.warning("no access_element found")

                time.sleep(10)
                try:
                    access_element = WebDriverWait(cls.driver, 5).until(
                        EC.element_to_be_clickable((AppiumBy.ID, "com.android.packageinstaller:id/permission_allow_button"))
                    )
                    access_element.click()

                except Exception as e:
                    logging.warning("no access_element found")

        return cls.driver

    @classmethod
    def get_driver(cls, username, password):
        #if cls.driver is None or cls.main_page is None or cls.username!=username:
        if cls.driver is None or not cls.is_session_active() or cls.username != username:
            cls.driver = cls._launch_app()
            cls.username=username
            if glo.get_value("skip_login")!='True':
                my_page = MainPage(cls.driver).to_my()
                my_page.login(username,password)
                my_page.to_main()
            return cls.driver
        else: # Todo: 逻辑需优化
            return cls.driver

    @classmethod
    def is_session_active(self):
        """判断session

        :return:
        """
        try:
            self.driver.session
            return True
        except Exception as e:
            return False
    # @classmethod
    # def get_main_page(cls):
    #     if cls.main_page is None:
    #         cls.get_driver()
    #     return cls.main_page

    @classmethod
    def quit(cls):
        """app退出"""
        if hasattr(cls,"driver"):
            cls.driver.quit()

